﻿using System.Collections.Generic;
using System.IO;
using System.Xml;
using Habanero.Base;
using Habanero.BO;
using Habanero.BO.ClassDefinition;

namespace FireStarterModeller.Logic
{
    public class XmlLoader : IBoLoader
    {
        private readonly TextReader _textReader;
        private readonly List<BusinessObject> _businessObjects = new List<BusinessObject>(5);

        public XmlLoader(TextReader textReader)
        {
            _textReader = textReader;
        }

        public void Load()
        {
            if (_textReader.Peek() == -1) return;
            XmlReader xmlReader = CreateXmlReader();
            //xmlReader.Name
            xmlReader.ReadStartElement();
            while (xmlReader.IsStartElement())
            {
                ReadNextBusinessObject(xmlReader);
            }
        }

        private void ReadNextBusinessObject(XmlReader xmlReader)
        {
            string className = XmlConvert.DecodeName(xmlReader.Name);
            ClassDef classDef = ClassDef.ClassDefs.FindByClassName(className);
            IBusinessObject businessObject = classDef.CreateNewBusinessObject();
            //TODO: What if no attributes
            xmlReader.MoveToFirstAttribute();
            do
            {
                string propertyName = xmlReader.Name;
                //string value = xmlReader.Value;
                object value = xmlReader.ReadContentAsObject();
                businessObject.SetPropertyValue(propertyName, value);
            } while (xmlReader.MoveToNextAttribute());
            businessObject.Save();
            _businessObjects.Add((BusinessObject) businessObject);
            xmlReader.Skip();
        }

        private XmlReader CreateXmlReader()
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreProcessingInstructions = true;
            settings.IgnoreWhitespace = true;
            return XmlReader.Create(_textReader, settings);
        }

        public List<BusinessObject> BusinessObjects
        {
            get { return _businessObjects; }
        }
    }
}